from django.http import JsonResponse
from Article.models import articles, favorite_user, like_user, comment
from Article.service import search
from django.views.decorators.csrf import csrf_exempt
import json
from django.core import serializers
from Article.form import CreationModelForm


# 作者发布文章
@csrf_exempt
def publishArticle(request):
    # 判断用户是否为 POST 提交数据
    if request.method == "POST":
        post_data = request.body  # POST方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型
        # 校验发布数据
        form = CreationModelForm(data=data)
        if form.is_valid():
            form.save()
            return JsonResponse({'code': 200, 'msg': "发布成功"})
        return JsonResponse({'code': 404, 'msg': form.errors})
    else:
        return JsonResponse({'code': 404, 'msg': "请求错误"})


# 其他用户搜索文章
def searchArticle(request):
    if request.method == "GET":
        post_data = request.body  # POST方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型
        keyword = data.get('keyword')
        articleList = search.search(keyword)
        # print(articleList)
        # print(type(articleList))
        # json序列化
        articleList_data = serializers.serialize('json', articleList)
        return JsonResponse({'code': 200, 'msg': '查询成功', 'data': articleList_data})
    return JsonResponse({'code': 404, 'msg': '查询失败'})


# 点赞功能实现
def likeArticle(request):
    articles_id = request.POST.get('article_id')
    user_id = request.POST.get('user_id')
    try:
        articles = articles_id.object.get(id=articles_id)
        if like_user.objects.filter(like_user_id='user_id').exists():
            return JsonResponse({'code': 404, 'msg': '您已点赞该文章'})
        else:
            articles.like_user.add(user_id)
            articles.save()
            likes_count = articles.like_users.count()
            return JsonResponse({'code': 200, 'msg': '点赞成功', 'data': likes_count})
    except:
        return JsonResponse({'code': 404, 'msg': '文章不存在'})


# 文章收藏功能
def favoriteArticle(request):
    articles_id = request.POST.get('article_id')
    user = request.user
    try:
        articles = articles_id.object.get(id=articles_id)
        if favorite_user.objects.filter(favorite_user_id='favorite_user_id').exists():
            return JsonResponse({'code': 404, 'msg': '您已收藏该文章'})
        else:
            articles.favorite_user.add(user)
            articles.save()
            favorite_count = articles.favorite_user.count()
            return JsonResponse({'code': 200, 'msg': '收藏成功', 'data': favorite_count})
    except:
        return JsonResponse({'code': 404, 'msg': '文章不存在'})


# 分页功能,主要写法交给前端做，前端传开始位置和结束位置，后端获取这个长度的数据并返回数据
def get_data(request):
    if request.method == 'GET':
        post_data = request.body  # GET方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型
        start = int(data.get('start', 0))
        articles_id = data.get('articles_id')
        end = int(data.get('end', 10))
        # print(data)
        count = articles.objects.filter(articles_id=articles_id).count()  # 获取数量
        if start > count:
            start = count
        if end > count:
            end = count
        # 查找数据
        information = articles.objects.filter(articles_id=articles_id).order_by('articles_date')[start:end]
        data = serializers.serialize('json', information)
        # print(information)
        # print(articles_id)
        # 返回数据data
        return JsonResponse({'code': 200, 'msg': '成功', 'data': data})
    return JsonResponse({'code': 404, 'msg': '请求错误'})


# 转发功能
def forwardArticle(request):
    if request.method == 'POST':
        url = request.POST.get('url')
        if url:
            try:
                # 发送GET请求获取页面内容
                response = request.get(url)
                # 将获取的内容返回给用户
                return JsonResponse({'code': 200, 'msg': '转发成功', 'date': response.text})
            except:
                return JsonResponse({'code': 400, 'msg': '请求失败'})
        else:
            return JsonResponse({'code': 404, 'msg': '缺少参数'})
    else:
        return JsonResponse({'code': 404, 'msg': '转发失败'})


# 评论功能
def commentArticle(request):
    if request.method == "POST":
        post_data = request.body
        data = json.loads(post_data)
        comment_context = data.get("comment_context")
        article_id = data.get("article_id")
        user_id = data.get("user_id")
        try:
            comment = comment(article_id=article_id, comment_content=comment_context, user_id =user_id)
            comment.save()
            articles.articles_comment_count += 1
            comment_saved_successfully = True
        except Exception as e:
            print(e)
            comment_saved_successfully = False
        if comment_saved_successfully:
            return JsonResponse({'code': 200, 'msg': '评论成功'})
        else:
            return JsonResponse({'code': 404, 'msg': '评论失败'})
    else:
        return JsonResponse({'code': 404, 'msg': '请求失败'})


# 删除评论
def delete_comment(request):
    post_data = request.body
    data = json.loads(post_data)
    user_id = data.get("user_id")
    comment_id = data.get("comment_id")
    try:
        comment = comment.objects.get(comment_id=comment_id)
        if comment.objects.filter(user_id=user_id).exists():
            articles.articles_comment_count -= 1
            comment.delete()
            return JsonResponse({'code': 200, 'msg': '删除成功'})
        else:
            return JsonResponse({'code': 404, 'msg': '失败，你没有删除权限'})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 404, 'msg': '评论不存在'})


# 主页显示
def home_page(request):
    if request.user.username:
        all_article_list = articles.objects.all()
        return JsonResponse({'code': 200, 'msg': '成功', 'date': all_article_list})
    else:
        return JsonResponse({'code': 404, 'msg': '未登录'})


# 文章详情
@csrf_exempt
def article_detail(request):
    if request.method == "POST":
        post_data = request.body  # POST方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型
        # 根据需要获取指定数据
        articles_id = data.get("articles_id")
        # 获取文章
        detail = articles.objects.filter(articles_id=articles_id).first()
        # 判断文章是否存在
        if detail is None:
            return JsonResponse({'code': 404, 'msg': '文章不存在'})
        # 浏览量 +1
        detail.articles_views += 1
        detail.save(update_fields=['articles_views'])
        # 使用django内置的序列化器将数据转换成JSON格式，由于序列化转换的是一个集合，而上面定义detail是用first获取的是一个
        # 所以用[]把detail转化为集合
        detail_data = serializers.serialize('json', [detail])
        # 获取与文章相关的评论并按评论时间倒序排序
        comments = comment.objects.filter(articles_id=articles_id).all().order_by('-comment_date')
        # 文章评论用了all，获取的不止一个已经是一个集合了，所以不需要用[]
        comments_data = serializers.serialize('json', comments)
        return JsonResponse({'code': 200, 'msg': '成功', 'data': detail_data, 'comments': comments_data})
    return JsonResponse({'code': 404, 'msg': '请求错误'})


# 删除文章
@csrf_exempt
def delete_article(request):
    if request.method == "POST":
        post_data = request.body  # POST方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型
        # 根据需要获取指定数据
        articles_id = data.get("articles_id")
        articles.objects.filter(articles_id=articles_id).delete()
        if articles.objects.filter(articles_id=articles_id).exists():
            return JsonResponse({'code': 404, 'msg': '删除失败'})
        else:
            return JsonResponse({'code': 200, 'msg': '删除成功'})
    return JsonResponse({'code': 404, 'msg': '请求错误'})


# 更新文章
@csrf_exempt
def update_article(request):
    # 判断用户是否为 POST 提交数据
    if request.method == "POST":
        post_data = request.body  # POST方法的数据都封装在了body中, 获取原始数据
        data = json.loads(post_data)  # JSON数据转换成Python数据类型,将字节流转换为字典
        # 根据需要获取指定数据
        articles_id = data.get("articles_id")
        # 获取需要修改的具体文章
        article = articles.objects.filter(articles_id=articles_id).first()
        new_articles_title = data.get("articles_title")
        new_articles_content = data.get("articles_content")
        new_articles_label = data.get("articles_label")
        # 替换
        article.articles_title = new_articles_title
        article.articles_content = new_articles_content
        article.articles_label = new_articles_label
        article.save()
        return JsonResponse({'code': 200, 'msg': '更新成功'})
    return JsonResponse({"code": 404, 'msg': '请求错误'})
